package sng.modules.view.components.city.logic.movement
{
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	import flash.utils.setTimeout;
	
	import masputih.pathfinding.astar.Node;
	
	import org.casalib.util.ArrayUtil;
	
	import sng.modules.view.components.city.logic.event.TileEvent;

	/**
	 * 随机移动
	 * 
	 */
	public class Wander extends TileMovement
	{
		private var _timer:Timer;
		private var _delay:Number;
		private var _aiMove:AIMove;

		public function Wander(delay:Number)
		{
			_delay = delay;
		}

		private function init():void
		{
			_tile.moveBehavior = this;
			if (_timer != null) {
				_timer.stop();
				_timer.removeEventListener(TimerEvent.TIMER_COMPLETE, pickDestination);
			}
			_timer = new Timer(_delay, 1);
			_timer.addEventListener(TimerEvent.TIMER_COMPLETE, pickDestination);
			_timer.start();
		}

		private function pickDestination(e:Event = null):void
		{
			//var nodes:Array = tile.cityView.astarGrid.nodes.toArray();
			var nodes:Array = tile.cityView.astarGrid.getWalkables();
			if(nodes.length>0)
			{
				var randomNode:Node = ArrayUtil.random(nodes);
				while (randomNode.walkable == false)
				{
					randomNode = ArrayUtil.random(nodes);
				}
				
				if(_aiMove == null){
					_aiMove = new AIMove();
					tile.addEventListener(TileEvent.CANT_MOVE, pickDestination);
					tile.addEventListener(TileEvent.MOVE_COMPLETE, onMoveComplete);
				}
				tile.moveBehavior = new AIMove();
				tile.moveTo(randomNode.column, randomNode.row, 0);
			}
			else
			{
				flash.utils.setTimeout(init,4000);
			}
			//trace("start:"+tile.x+","+tile.y);
			//trace("start:"+tile.column+","+tile.row);
		}
		
		
		private function onMoveComplete(e:TileEvent):void
		{
			init();
			//trace("over:"+tile.x+","+tile.y);
			//trace("over:"+tile.column+","+tile.row);
		}

		override public function execute(params:Array = null):void
		{
			init();
		}

	}

}